// pages/confirm_order/confirm_order.js
const app = getApp();
import { u_Reg } from '../../config/tool.js';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    once: true, // 防止重复
    closeNote: false, // 是否提示过使用优惠券
    hasAddress: false, // 是否有地址
    is_status: 1, // 商品类型 1配送 2自提
    route: 0, // 从哪里来 1从购物车点击 2直接购买 3vip专区
    goodsInfo: '', // 附带的参数
    infos: '' , // 订单数据
    address: '', // 地址
    stores: '', // 门店信息
    person: '', // 提货人姓名
    tel: '', // 提货人电话
    school_contacts: '', // 提货人姓名
    school_mobile: '', // 提货人电话
    leavemsg: '', // 留言
    show: false, // 是否展示优惠券弹窗
    coupons: [], // 优惠券列表
    couponId: '', // 选中优惠券id
    cutPrice: '', // 优惠金额
    couponName: '请选择优惠券', // 选中优惠券名称
    totalprice: '', // 支付金额
    logisticsTotal: '', // 配送金额
    storeTotal: '', // 自提金额
    sendType: 1, // 配送方式 1两种都有 2商家配送 3自提
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    if (options.sendType){
      this.setData({
        sendType: options.sendType
      })
    }
    // 商品详情来的
    if (options.from == 'detail'){
      this.setData({
        route: 2,
        goodsInfo: JSON.parse(options.data)
      })
    }
    // 套餐下单
    if (options.from == 'vip'){
      this.setData({
        route: 3,
        goodsInfo: JSON.parse(options.data)
      })
    }
    // 购物车
    if (options.from == 'cart'){
      this.setData({
        route: 1,
        goodsInfo: JSON.parse(options.data)
      })
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getData();
    this.getStores();
  },

  // 获取门店信息
  getStores(){
    let that = this;
    wx.request({
      url: app.baseURL + 'order/getConfirmOrder',
      data: {
        token: app.globalData.userId,
        status: that.data.route == 3 ? 2 : that.data.route, // 1购物车 2直接购买 3vip专区
        type: that.data.goodsInfo.type, // 1）正常商品 2）限时抢购 4)2人团购-团购 5）团购单独购买
        is_status: 2, // 1配送商品 2自取商品

        // 购物车购买
        shoping_cart_ids: that.data.route == 1 ? that.data.goodsInfo.ids : '', // 购物车id

        // 直接购买
        goods_id: that.data.route != 1 ? that.data.goodsInfo.goods_id : '', // 商品id
        goods_spec_id: that.data.route != 1 ? that.data.goodsInfo.goods_spec_id : '', // 商品规格id
        num: that.data.route != 1 ? that.data.goodsInfo.num : '',  // 商品数量
        activity_id: that.data.route == 2 ? that.data.goodsInfo.marketing_id : '', // 活动id
        group_id: that.data.route == 2 ? that.data.goodsInfo.group_id : '', // 拼团活动id

        lng: wx.getStorageSync('location') ? JSON.parse(wx.getStorageSync('location')).longitude : '',
        lat: wx.getStorageSync('location') ? JSON.parse(wx.getStorageSync('location')).latitude : '',

        // 校园专区
        school_id: that.data.goodsInfo.school_id ? that.data.goodsInfo.school_id : ''
      },
      success(data) {
        let res = data.data;
        if (res.code == 1) {

          // 选择门店
          if (wx.getStorageSync('selectStore')) {
            that.setData({
              stores: JSON.parse(wx.getStorageSync('selectStore'))
            })
            wx.removeStorageSync('selectStore');
          }else{

            that.setData({
              stores: res.data.address,
            })
          }
          that.setData({
            storeTotal: res.data.totalprice, // 默认totalprice 值为配送金额
          })
          if (that.data.is_status == 2) {
            that.setData({
              totalprice: that.data.cutPrice ? (Number(that.data.storeTotal) - Number(that.data.cutPrice)).toFixed(2) : that.data.storeTotal
            })
          }
        } else {
          app.$tip(res.msg);
        }
      }
    })
  },

  // 获取数据
  getData(){
    let that = this;
    app.loading();
    wx.request({
      url: app.baseURL + 'order/getConfirmOrder',
      data: {
        token: app.globalData.userId,
        status: that.data.route == 3 ? 2 : that.data.route, // 1购物车 2直接购买 3vip专区
        type: that.data.goodsInfo.type, // 1）正常商品 2）限时抢购 4)2人团购-团购 5）团购单独购买
        is_status: 1, // 1配送商品 2自取商品

        // 购物车购买
        shoping_cart_ids: that.data.route == 1 ? that.data.goodsInfo.ids : '', // 购物车id

        // 直接购买
        goods_id: that.data.route != 1 ? that.data.goodsInfo.goods_id : '', // 商品id
        goods_spec_id: that.data.route != 1 ? that.data.goodsInfo.goods_spec_id : '', // 商品规格id
        num: that.data.route != 1 ? that.data.goodsInfo.num : '',  // 商品数量

        activity_id: that.data.route == 2 ? that.data.goodsInfo.marketing_id : '', // 活动id
        group_id: that.data.route == 2 ? that.data.goodsInfo.group_id : '', // 拼团活动id

        // 校园专区
        school_id: that.data.goodsInfo.school_id ? that.data.goodsInfo.school_id : ''
      },
      success(data){
        let res = data.data;
        wx.hideLoading();
        if(res.code == 1){
          if(res.data.address){
            that.setData({
              hasAddress: true,
              address: res.data.address
            })
          }
          // 选择地址
          if (wx.getStorageSync('selectAddress')){
            that.setData({
              hasAddress: true,
              address: JSON.parse(wx.getStorageSync('selectAddress'))
            })
            wx.removeStorageSync('selectAddress');
          }

          that.setData({
            infos: res.data,
            logisticsTotal: res.data.totalprice,
            coupons: res.data.coupon_list
          })
          if (that.data.is_status == 1){
            that.setData({
              totalprice: that.data.cutPrice ? (Number(that.data.logisticsTotal) - Number(that.data.cutPrice)).toFixed(2) : that.data.logisticsTotal
            })
          }
        }else{
          app.$tip(res.msg);
        }
      }
    })
  },

  // 选择配送方式
  chooseType(e){
    this.setData({
      is_status: e.currentTarget.dataset.type
    })
    // 配送金额
    if(e.currentTarget.dataset.type == 1){
      this.setData({
        totalprice: this.data.cutPrice ? (Number(this.data.logisticsTotal) - Number(this.data.cutPrice)).toFixed(2) : this.data.logisticsTotal
      })
    }else{
      // 自提金额
      this.setData({
        totalprice: this.data.cutPrice ? (Number(this.data.storeTotal) - Number(this.data.cutPrice)).toFixed(2) : this.data.storeTotal
      })
    }
  },

  // 选择地址
  toAddress(){
    if (this.data.goodsInfo.school_id){
      wx.navigateTo({
        url: '/pages/delivery_address/delivery_address?type=1&schoolId=' + this.data.goodsInfo.school_id,
      })
    }else{
      wx.navigateTo({
        url: '/pages/delivery_address/delivery_address?type=1',
      })
    }
  },

  // 输入姓名
  initPerson(e){
    if(this.data.goodsInfo.school_id){
      this.setData({
        school_contacts: e.detail.value
      })
    }else{
      this.setData({
        person: e.detail.value
      })
    }
  },

  // 输入电话
  initTel(e){
    if (this.data.goodsInfo.school_id) {
      this.setData({
        school_mobile: e.detail.value
      })
    }else{
      this.setData({
        tel: e.detail.value
      })
    }
  },

  // 选择门店
  toStores(){
    wx.navigateTo({
      url: '/pages/store_pick/store_pick',
    })
  },

  // 输入留言
  initMsg(e){
    this.setData({
      leavemsg: e.detail.value
    })
  },

  // 展示优惠券弹窗
  showCoupons(){
    this.setData({
      show: true
    })
  },

  // 选择优惠券
  selectCoupon(e){
    let id = e.currentTarget.dataset.id,
      price = e.currentTarget.dataset.price,
      name = e.currentTarget.dataset.name;
    this.setData({
      couponId: id == -9999 ? '' : id,
      cutPrice: price,
      couponName: name
    })
  },

  // 确定选择
  selected(){
    this.setData({
      show: false,
    })

    // 选择优惠券后计算总价
    // 判断订单里有没有活动商品 有要减去活动商品
    // 配送
    if (this.data.is_status == 1){
      this.setData({
        totalprice: (Number(this.data.logisticsTotal) - Number(this.data.cutPrice)).toFixed(2)
      })
    }else{
      this.setData({
        totalprice: (Number(this.data.storeTotal) - Number(this.data.cutPrice)).toFixed(2)
      })
    }
  },

  // 关闭弹窗
  closed(){
    this.setData({
      show: false
    })
  },

  // 提交订单
  submitOrder(){
    let that = this;
    if(that.data.is_status == 1 && !this.data.address){
      app.$tip('请选择地址!');
      return
    }

    if(that.data.is_status == 2){
      if(that.data.goodsInfo.school_id){
        if (!this.data.school_contacts){
          app.$tip('请输入提货人姓名!');
          return
        }
        if (!this.data.school_mobile){
          app.$tip('请输入预留手机号!');
          return
        }
        if (!u_Reg(this.data.school_mobile, 'phone')){
          app.$tip('请输入正确的手机号!');
          return
        }
      }else{
        if (!this.data.person){
          app.$tip('请输入提货人姓名!');
          return
        }
        if (!this.data.tel){
          app.$tip('请输入预留手机号!');
          return
        }
        if (!u_Reg(this.data.tel, 'phone')){
          app.$tip('请输入正确的手机号!');
          return
        }
      }
    }

    // 有优惠券却未使用时提示
    if (that.data.infos.coupon_status == 1 && !that.data.couponId){
      // 判断是否提示过了
      // 没有提示过 提示
      if (!that.data.closeNote){
        wx.showModal({
          title: '温馨提示',
          content: '您有优惠券尚未使用!',
          confirmText: '下次再说',
          confirmColor: '#57b127',
          cancelText: '去使用',
          success(res) {
            if (res.confirm) {
              that.makeOrder();
            }
            if (res.cancel) {
              that.setData({
                closeNote: true
              })
            }
          }
        })
      }else{
        // 提示过 下一步
        that.makeOrder();
      }
      
    }else{
      that.makeOrder();
    }
  },

  // 下单
  makeOrder(){
    let that = this;
    if (that.data.once) {
      app.loading();
      that.setData({
        once: false
      })
      wx.request({
        url: app.baseURL + 'order/setProductionOrder',
        data: {
          token: app.globalData.userId,
          status: that.data.infos.status, // 从哪里来 1购物车 2直接购买
          is_status: that.data.is_status, // 配送方式 1商家配送 2自提
          remark: that.data.leavemsg, // 留言
          // 自提时传
          consignee: that.data.goodsInfo.school_id ? that.data.school_contacts : that.data.person, // 提货人
          reserved_telephone: that.data.goodsInfo.school_id ? that.data.school_mobile : that.data.tel, // 预留电话
          apply_id: that.data.is_status == 2 ? that.data.stores.id : '', // 代理商提货地址id

          address_id: that.data.is_status == 1 ? that.data.address.address_id : '', // 地址ID
          totalprice: that.data.totalprice ? that.data.totalprice : that.data.infos.totalprice, // 总金额
          // 从购物车来时传
          shoping_cart_ids: that.data.route == 1 ? that.data.goodsInfo.ids : '', //购物车ID，多个逗号隔开
          // 直接购买传
          goods_id: that.data.route != 1 ? that.data.goodsInfo.goods_id : '', // 商品ID
          goods_spec_id: that.data.route != 1 ? that.data.goodsInfo.goods_spec_id : '', // 规格ID
          num: that.data.route != 1 ? that.data.goodsInfo.num : '', // 数量
          activity_id: that.data.route == 2 ? that.data.goodsInfo.marketing_id : '', // 活动id

          type: that.data.goodsInfo.type, // 1正常商品 2限时抢购 4两人团 5团购单独买 6套餐下单
          coupon_id: that.data.couponId ? that.data.couponId : '', // 优惠券id
          freight: that.data.is_status == 1 ? that.data.infos.freight : '', // 运费

          // 校园专区
          school_id: this.data.goodsInfo.school_id?this.data.goodsInfo.school_id:'0'
        },
        success(data) {
          let res = data.data;
          wx.hideLoading();
          that.setData({
            once: true
          })
          if (res.code == 1) {
            wx.redirectTo({
              url: '/pages/orderpay/orderpay?data=' + JSON.stringify(res.data),
            })
          } else {
            app.$tip(res.msg);
          }
        }
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    wx.removeStorageSync('selectAddress');
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

})